<template>
	<globalModal
		:title="title"
		:visible="visible"
		:confirmLoading="confirmLoading"
		@ok="handleOk"
		@cancel="handleCancel"
	>
		<a-spin :spinning="confirmLoading">
			<a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<a-form-item label="机构名称">
					<a-input
						placeholder="请输入机构名称"
						v-decorator="[
							'orgName',
							{
								rules: [
									{ required: true, message: '机构名称' },
									{ max: 50, message: '机构名称不超过50个字符' },
								],
								getValueFromEvent: removeSpaces,
							},
						]"
					/>
				</a-form-item>

				<a-form-item label="启停用状态">
					<a-select
						v-decorator="[
							'status',
							{ initialValue: '0', rules: [{ required: true, message: '请选择状态' }] },
						]"
						placeholder="请选择状态"
					>
						<a-select-option value="0">启用</a-select-option>
						<a-select-option value="1">停用</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="系统名称">
					<a-input
						placeholder="请输入系统名称"
						v-decorator="[
							'sysName',
							{
								rules: [
									{ required: true, message: '系统名称' },
									{ max: 50, message: '系统名称不超过50个字符' },
								],
								getValueFromEvent: removeSpaces,
							},
						]"
					/>
				</a-form-item>
				<a-form-item label="系统Logo">
					<!-- <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :before-upload="beforeUpload" :customRequest="uploadImage">
						<img v-if="imageUrl" :src="imageUrl" alt="avatar" style=" width: 128px;height: 128px;" />
						<div v-else>
							<a-icon :type="loading ? 'loading' : 'plus'" />
							<div class="ant-upload-text">上传图片</div>
						</div>
					</a-upload> -->
					<a-upload
						list-type="picture-card"
						class="avatar-uploader"
						:show-upload-list="false"
						:before-upload="beforeUpload"
						v-decorator="[
							'logUrl',
							{ rules: [{ required: false, message: '上传图片' }], valuePropName: 'logUrl' },
						]"
					>
						<img
							v-if="orgLogo"
							:src="fileUrl + orgLogo.split(';')[0]"
							alt="avatar"
							style="width: 128px; height: 128px"
						/>
						<div v-else>
							<a-icon :type="loading ? 'loading' : 'plus'" />
							<div class="ant-upload-text">上传图片</div>
						</div>
					</a-upload>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效期">
					<a-range-picker
						v-decorator="['expiredDate', { rules: [{ required: false, message: '请选择有效期' }] }]"
						class="w100"
					/>
					<!-- <j-date class="w100" v-decorator="['expiredDate']" placeholder="请选择有效期" date-format="YYYY-MM-DD"></j-date> -->
				</a-form-item>
				<a-form-item label="机构地址">
					<a-cascader
						v-decorator="[
							'geo',
							{
								rules: [{ required: true, message: '请选择机构地址' }],
							},
						]"
						@change="changeAddr"
						:options="areaData"
						:load-data="loadData"
						change-on-select
						:field-names="{ label: 'xzqhmc', value: 'xzqhbm', children: 'children' }"
						style="width: 100%"
						placeholder="机构地址"
					>
						<template slot="displayRender" slot-scope="{ labels, selectedOptions }">
							<span v-for="(label, index) in labels" :key="selectedOptions[index].value">{{
								label
							}}</span>
						</template>
					</a-cascader>
				</a-form-item>
			</a-form>
		</a-spin>
	</globalModal>
</template>

<script>
function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onload = () => resolve(reader.result)
		reader.onerror = (error) => reject(error)
	})
}
import { ModalMixins } from '@/mixins'
import { PhoneReg } from '@/utils/validate.js'
import { sysUrl } from '@/api/index.js'
import { sysManageapi } from '@/api/index.js'
let cache = {}
export default {
	name: 'addOrEditOrgModal',
	mixins: [ModalMixins],
	data() {
		return {
			PhoneReg,
			loading: false,
			orgLogo: '',
			fileUrl: process.env.VUE_APP_FILE_API,
			objectData: {
				OSSAccessKeyId: '',
				policy: '',
				Signature: '',
				key: '',
				host: '',
				dir: '',
			},
			salesTypeList: [], //销售类型
			areaData: [],
		}
	},
	components: {},
	methods: {
		initInfo(record = {}) {
			this.mdl = Object.assign({}, record)
			this.mdl.salesType = this.mdl.salesType ? this.mdl.salesType.toString() : undefined
			this.title = (this.isAdd ? '新增' : '编辑') + this.modalTitle
			this.visible = true
			this.orgLogo = record.logUrl
			//获取一些初始下拉数据
			this.getDefaultList && this.getDefaultList()
		},

		async getDefaultList() {
			let { province, city, area } = this.mdl
			if (province && city && area) {
				this.mdl.geo = [province, city, area]
			}
			let areaData = await this.getCitysInfo('')
			if (province) {
				let provinceIndex = areaData.findIndex((item) => item.xzqhbm == province)
				if (provinceIndex > -1) {
					areaData[provinceIndex].children = await this.getCitysInfo(province)
					if (city) {
						let index = areaData[provinceIndex].children.findIndex((item) => item.xzqhbm == city)
						if (index > -1) {
							areaData[provinceIndex].children[index].children = await this.getCitysInfo(city)
						}
					}
				}
			}
			this.areaData = [...areaData]
			this.$nextTick(() => {
				this.form.resetFields()
				this.setFieldsValue()
				if (this.mdl.startDate) {
					this.form.setFieldsValue({ expiredDate: [moment(this.mdl.startDate), moment(this.mdl.endDate)] })
				}
			})
		},

		// 上传头像前校验
		beforeUpload(file) {
			const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
			if (!isJpgOrPng) {
				this.$message.error('只能上传jpg/png格式的图片')
				return
			}
			const isLt10M = file.size / 1024 / 1024 < 10
			if (!isLt10M) {
				this.$message.error('图片不得大于10MB!')
				return
			}
			this.uploadFiles(file)
			return false
			/* return isJpgOrPng && isLt10M; */
		},
		uploadFiles(file) {
			/* let fileList = [];
			fileList = [file] */
			let formdata = new FormData()
			/* if (fileList && fileList.length > 0) {
				for (var i = 0; i < fileList.length; i++) {
					formdata.append('file', fileList[i]);
				}
			} else {
				formdata.append('file', null);
			} */
			formdata.append('file', file)
			this.$postActionUpload(this.$api.uploadFile, formdata)
				.then((res) => {
					if (res.code == 1) {
						this.orgLogo = res.data
						this.$message.success('上传成功')
					}
				})
				.catch((err) => {})
				.finally((res) => {})
		},

		/**
		 * 点击确认按钮
		 */
		handleOk() {
			// 触发表单验证
			this.form.validateFields((err, values) => {
				// 验证表单没错误
				if (!err) {
					/* 处理地址 */
					let id = this.mdl[this.editKey]
					let parameter = Object.assign(
						{},
						values,
						{ logUrl: this.orgLogo },
						id
							? {
									[this.editKey]: id,
							  }
							: ''
					)
					if (values.expiredDate && values.expiredDate.length > 0) {
						parameter.startDate = values['expiredDate'][0].format('YYYY-MM-DD') + ' 00:00:00'
						parameter.endDate = values['expiredDate'][1].format('YYYY-MM-DD') + ' 23:59:59'
					} else {
						parameter.startDate = ''
						parameter.endDate = ''
					}
					let geo = values['geo']
					parameter.province = geo && geo.length > 2 ? geo[0] : null
					parameter.city = geo && geo.length > 2 ? geo[1] : null
					parameter.area = geo && geo.length > 2 ? geo[2] : null
					this.saveInfo(this.isAdd ? this.api.add : this.api.edit, parameter)
				}
			})
		},
		getCitysInfo(id) {
			return new Promise((resolve, reject) => {
				let key = 'address_' + id
				if (cache[key] && cache[key].length > 0) {
					resolve(cache[key])
				} else {
					this.getCitys(id)
						.then((res) => {
							// console.log('res', res);
							let list = res.data.map((item) => {
								return {
									...item,
									isLeaf: item.level == 3,
								}
							})
							cache[key] = list
							resolve(list)
						})
						.catch((err) => {
							reject(err)
						})
				}
			})
		},
		async loadData(selectedOptions) {
			const targetOption = selectedOptions[selectedOptions.length - 1]
			// console.log('e', 'haha', targetOption);
			targetOption.loading = true
			let addressList = await this.getCitysInfo(targetOption.xzqhbm)
			targetOption.loading = false
			targetOption.children = addressList
			this.areaData = [...this.areaData]
		},
		getCitys(cid) {
			return this.$postAction(sysManageapi.deptUrl.getRegion + '?pXzqhbm=' + cid)
		},
		changeAddr(e, selectedOptions) {
			// let xzqhbm = '';
			// if (selectedOptions && selectedOptions.length > 0) {
			// 	xzqhbm = selectedOptions[selectedOptions.length - 1].code;
			// }
			// console.log('e', e, selectedOptions, xzqhbm);
			// this.form.setFieldsValue({
			// 	xzqhbm
			// });
		},
	},
}
</script>

<style scoped></style>
